package pkg

import (
	"fmt"
	"github.com/golang-jwt/jwt/v5"
	"time"
)

// @secretKey: JWT 加解密密钥
// @iat: 时间戳
// @seconds: 过期时间，单位秒
// @payload: 数据载体
func GetJwtToken(userId int) (string, error) {
	iat := time.Now().Unix()
	claims := make(jwt.MapClaims)
	claims["exp"] = iat + 86400
	claims["iat"] = iat
	claims["userId"] = userId
	token := jwt.New(jwt.SigningMethodHS256)
	token.Claims = claims
	secretKey := "123456"
	return token.SignedString([]byte(secretKey))
}
func ParseJwtToken(tokenString string) (float64, error) {
	token, err := jwt.Parse(tokenString, func(token *jwt.Token) (any, error) {
		secretKey := "123456"
		return []byte(secretKey), nil
	}, jwt.WithValidMethods([]string{jwt.SigningMethodHS256.Alg()}))
	if err != nil {
		return 0, fmt.Errorf("未登录")
	}
	if claims, ok := token.Claims.(jwt.MapClaims); ok {
		return claims["userId"].(float64), err
	} else {
		fmt.Println("未登录")
	}
	return 0, nil
}
